package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //过滤器类型:  pre,routing,post,error
    @Override
    public String filterType() {
       // return "pre";
        return FilterConstants.PRE_TYPE;
    }
    //过滤器的顺序号
    @Override
    public int filterOrder() {
        return 6;//默认已经有5个前置过滤器
    }
    //判断当前请求,是否需要执行下面的过滤代码
    @Override
    public boolean shouldFilter() {
        //调用商品,执行权限判断;
        //调用用户或者订单,不执行判断

        //获得当前请求的上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文对象获得调用的 service id
        String serviceId =(String)ctx.get("serviceId");
        //判断service id是否是"item-service"
        return "item-service".equalsIgnoreCase(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //获得当前请求的上下文对象
        RequestContext cxt = RequestContext.getCurrentContext();
        //从上下文得到request对象
        HttpServletRequest request = cxt.getRequest();
        //从request获取jwt参数
        String jwt = request.getParameter("jwt");
        //如果参数不存在,阻止继续调用,直接返回响应
        if (StringUtils.isBlank(jwt)) {
            //阻止继续调用
            cxt.setSendZuulResponse(false);
            //直接返回响应
            String json = JsonResult.build().code(403).msg("没有登录").toString();
            cxt.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");
            cxt.setResponseBody(json);
        }
        return null;
    }
}
